package team.zero.lemon.common.MQ.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import team.zero.lemon.common.utils.JsonUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.*;
import java.io.Serializable;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by fangpingxi on 2017/9/23.
 */
public abstract class BaseTopicConsumer<T extends Serializable> {

    @Autowired
    @Qualifier("mqConnectionFactory")
    private ConnectionFactory connectionFactory;
    private MessageConsumer consumer;
    private Connection connection = null;
    private Session session = null;

    @PostConstruct
    private void init() {
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(getTopicName());
            consumer = session.createConsumer(destination);
            startListener();
        } catch ( JMSException e ) {
            clearResource();
        }
    }

    private void startListener() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 设置接收者接收消息的时间，为了便于测试，这里谁定为100s
                    try {
                        TextMessage textMessage = (TextMessage) consumer.receive(500000);
                        if (null != textMessage) {
                            T message = JsonUtils.JsonToObject(textMessage.getText(), getClassType());
                            handleMessage(message);
                        } else {
                            break;
                        }
                    } catch ( Exception ex ) {

                    }
                }
            }
        }).start();
    }


    private void clearResource() {
        if (consumer != null) {
            try {
                consumer.close();
            } catch ( JMSException e ) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch ( JMSException e1 ) {
                e1.printStackTrace();
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch ( JMSException e1 ) {
                e1.printStackTrace();
            }
        }
    }

    @PreDestroy
    private void end() {
        clearResource();
    }


    public abstract String getTopicName();

    public abstract Class<T> getClassType();

    public abstract void handleMessage(T message);
}
